package br.com.freelancer.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

/**
 *
 * @author tiago nogueira
 */
public class TextFileHelper {

	public static String getFile(File fl) throws Exception {
		return getFile(fl,"utf-8");
	}
	public static byte[] getFileBytes(InputStream fileName,String CharSet)throws Exception{
		try{
			byte b[]=new byte[fileName.available()];
			fileName.read(b);
			return b;
		}
		catch(Exception ex){
			throw ex;
		}
		finally{
			if(fileName!=null) fileName.close();
		}
	}
	public static String getFile(File fl,String CharSet)throws Exception{
		FileInputStream file=null;
		try{

			file=new FileInputStream(fl);
			byte b[]=new byte[(int)fl.length()];
			file.read(b);
			return new String(b,CharSet);
		}
		catch(Exception ex){
			throw ex;
		}
		finally{
			if(file!=null) file.close();
		}
	}
	public static void saveFile(String fl,String CharSet,String content)throws Exception{
		saveFile(new File(fl),CharSet,content);
	}
	public static void saveFile(String fl,String content)throws Exception{
		saveFile(new File(fl),"UTF-8",content);
	}
	public static void saveFile(File fl,String CharSet,String content)throws Exception{
		FileOutputStream file=null;
		try{

			file=new  FileOutputStream(fl);
			file.write(content.getBytes(CharSet));

		}
		catch(Exception ex){
			throw ex;
		}
		finally{
			if(file!=null) file.close();
		}
	}

	public static String convertStreamToString(final InputStream is, final String encoding) throws IOException {
		if (ObjectHelper.isNotNull(is)){ 
			Writer writer = new StringWriter(); 
			char[] buffer = new char[1024]; 
			try {
				Reader reader = new BufferedReader( new InputStreamReader(is, encoding)); 
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n); 
				}

			}finally {
				is.close(); 
			}
			return writer.toString(); 
		}else {
			return "";
		}
	}
	
}
